import axios from "axios";
import {router} from "../router/index.js";

// export const baseUrl = '/dev-api'
export const baseUrl = 'api'
const service = axios.create({
    baseURL: baseUrl, // dev-api，代理到测试环境
    timeout: 5 * 1000, // 五秒超时时间
});
/**
 * 请求拦截
 */
service.interceptors.request.use(
    config => {
        const token = localStorage.getItem("token");
        console.log("请求头", token)
        if (token) {
            config.headers.setAuthorization("Bearer " + token);
        }
        if (!config.url.startsWith("/gateway")) {
            config.url = "/gateway" + config.url;
        }
        config.headers.setContentType("application/json");
        return config;
    })

/**
 * 响应拦截
 */
service.interceptors.response.use(
    resopnse => {
        const data = resopnse.data;
        // 跳转登陆页面
        if (data?.code === 401) {
            router.replace({path: '/login'})
        }
        return resopnse.data;
    }
)
export default service